# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

# cos opsration func 

from urllib import response
import utils.config.websvrini as ini
import utils.common.initres as initres
import utils.common.func as func
import utils.common.log as log
from regex import F
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

secret_id = ''
secret_key = ''
region = 'ap-nanjing'


class WebBucket:  # web 存储桶
    def __init__(self, secret_id, secret_key, region, bucket_name):
        """
        secret_id :  
        secret_key :  
        region :  
        bucket : 
        """
        token = None 
        scheme = 'https'  
        self.endpoint = ""
        self.bucket_name = bucket_name
        config = CosConfig(Region=region, SecretId=secret_id,SecretKey=secret_key,Token=token, Scheme=scheme)
        self.__client = CosS3Client(config)

    def list_bucket(self):
         
        return self.__client.list_buckets()

    def upload_file(self, file_path, save_path) -> bool :
         # 上传文件
        res = self.__client.upload_file(
            Bucket=self.bucket_name,   
            LocalFilePath=file_path,   
            Key=save_path,   
            PartSize=1,   
            MAXThread=10,   
            EnableMD5=False
        )

        url = f"https://{self.bucket_name}.cos.ap-nanjing.myqcloud.com/{save_path}"
        print(res)
        if 'ETag' in res :
            log.logging.info(("ETag : " + res['ETag'] + "  ; "+ save_path + " upload ok"))
            return True, url
        else:
            log.logging.error(("upload failed, res.status: " + res))
            return False, ""

    def remove_file(self, cos_obj_name):
        """
        not used func
        """
        res = self.__client.delete_object(
            Bucket=self.bucket_name,  
            Key=cos_obj_name   
        )

        return res

    def get_url(self, file_path):
        url = self.__client.get_object_url(
            Bucket=self.bucket_name,
            Key=file_path
        )
        return url

_templateCOS = None
_webCOS = None
if  initres.COS_TYPE :  # True
    iniPath = ''
    iniPath=initres.iniPath()  # 获取[cos]配置文件路径 /cfg/vlog_Config.ini
    
    _templateDic = ini.get_cos(iniPath)
    # _templateCOS = WebBucket(_templateDic['secret_id'], _templateDic['secret_key'],_templateDic['region'],_templateDic['template_bucket'], '')
    # 创建 cos 实例
    _webCOS = WebBucket(_templateDic['secret_id'], _templateDic['secret_key'],_templateDic['region'],_templateDic['web_bucket'])
    

def upload_template(filename):
    # 上传模板
    if _templateCOS is not None:
        ok, retname = _templateCOS.shadow_upload(filename)
    else:
        retname = initres.localUrl + filename.split("/")[-1]
    
    return retname

def delete_template(filename):
     
    if _templateCOS is not None:
        print(filename)
        retname = _templateCOS.remove_file(filename)
    return retname

def upload_webRes(filename):
    # 上传前端静态资源
    
    if _webCOS is not None:
            ok, retname = _webCOS.upload_file(filename,filename)
    else:
        retname = initres.localUrl + filename.split("/")[-1]
        
    log.logging.info(retname)
    return retname

def delete_webRes(filename):
     
    if _webCOS is not None:
        print(filename)
        retname = _webCOS.remove_file(filename)
    return retname





if __name__ == '__main__':
    key = WebBucket(secret_id, secret_key, region, 'test-1309946842')
    # print(key.list_bucket())
    print(key.upload_file("/home/vlogmanagement/daily.log", "test/daily.log"))
    key.del_file("daily.log")
